package com.imooc.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.imooc.pojo.R;

@ControllerAdvice
public class WebExceptionController {

	/**
	 * 渲染页面模板
	 * @param ex
	 * @return
	 */
//	@ExceptionHandler(value = Exception.class)
//	public ModelAndView myErrorHandler(HttpServletRequest req, Exception e) {
//	   e.printStackTrace();
//		
//		ModelAndView modelAndView = new ModelAndView();
//	    modelAndView.setViewName("freemarker/error");
//	    modelAndView.addObject("code", e);
//	    modelAndView.addObject("url", req.getRequestURL());
//	    return modelAndView;
//	}
	
	/**
	 * 判断请求是否是AJAX，还是渲染页面模板
	 * @param ex
	 * @return
	 */
//	@ExceptionHandler(value=Exception.class)
//	public Object errorHandler(HttpServletRequest req,
//			Exception e) throws Exception{
//		e.printStackTrace();
//		return R.errorException(e.getMessage());
		
//		if(isAjax(req)){
//			System.out.println("======ajax==========");
//			return R.errorException(e.getMessage());
//		}else{
//			System.out.println("======web==========");
//			ModelAndView modelAndView = new ModelAndView();
//		    modelAndView.setViewName("freemarker/error");
//		    modelAndView.addObject("code", e);
//		    modelAndView.addObject("url", req.getRequestURL());
//		    return modelAndView;
//		}
//	}
	
	
	/**
	 * 判断请求是否是ajax请求
	 */
	public static boolean isAjax(HttpServletRequest req){
		return req.getHeader("X-Requested-With") != null
				&& "XMLHttpRequest"
				.equals(req.getHeader("X-Request-With"));
	}
	
}
